package com.gxa.saas.portal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.saas.core.entity.dto.luoj.ProductDTO;
import com.gxa.saas.core.entity.dto.luoj.ShoppingCart;
import com.gxa.saas.core.entity.dto.luoj.ShoppingCartItem;
import com.gxa.saas.core.entity.dto.luoj.TbAddressDTO;
import com.gxa.saas.core.entity.vo.luoj.OrderCartVO;
import com.gxa.saas.portal.mapper.AddressMapper;
import com.gxa.saas.portal.mapper.OrderCartMapper;
import com.gxa.saas.portal.mapper.ShoppingCartMapper;
import com.gxa.saas.portal.service.ShoppingCartService;
import com.gxa.saas.portal.util.Uuid;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Validated
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private OrderCartMapper orderCartMapper;

    public static final String SHOPPINGCART_KEY="ShoppingCart_key";
    public static final String SHOPPINGCART_NAME="ShoppingCart:userId:";

    @Override
    public void addProduct(@Validated ProductDTO product)  {
        //获取对象
        ShoppingCart cart = getShoppingCart(product.getUserId());
        ShoppingCart newCart = null;
        if(cart==null){
            newCart = new ShoppingCart();
            newCart.setUserId(product.getUserId());
            ShoppingCartItem cartItem = new ShoppingCartItem(product.getId(),product.getCount(),product.getPrName(),product.getPrPrice(),product.getPrStore(),product.getPicture(),product.getColorName(),product.getSpeName());
            newCart.getCartItems().add(cartItem);
            BigDecimal newTotal = product.getPrPrice().multiply(BigDecimal.valueOf(product.getCount())) ;
            newCart.setTotalPrice(newTotal);
            newCart.setTotalNum(product.getCount());
        }else {
            //TODO List改Set
            newCart=cart;
            List<ShoppingCartItem> cartItems = newCart.getCartItems();
            boolean isHave = false;
            BigDecimal total = newCart.getTotalPrice();//总价
            for (int i = 0; i < cartItems.size(); i++) {
                if(cartItems.get(i).getProductId().equals(product.getId())){
                    cartItems.get(i).setProductCount(cartItems.get(i).getProductCount()+1);
                    total=total.add(cartItems.get(i).getPrice());
                    newCart.setTotalNum(newCart.getTotalNum()+1);//总数
                    isHave = true;
                    break;
                }
            }
            if(!isHave){
                ShoppingCartItem cartItem = new ShoppingCartItem(product.getId(),product.getCount(),product.getPrName(),product.getPrPrice(),product.getPrStore(),product.getPicture(),product.getColorName(),product.getSpeName());
                newCart.setTotalNum(newCart.getTotalNum()+product.getCount());
                total = total.add(product.getPrPrice().multiply(BigDecimal.valueOf(product.getCount())));
                newCart.setTotalPrice(total);
                newCart.getCartItems().add(cartItem);
            }
            newCart.setTotalPrice(total);
        }
            redisTemplate.opsForHash().put(SHOPPINGCART_KEY,SHOPPINGCART_NAME+product.getUserId(),newCart);
    }

    @Override
    public ShoppingCart getShoppingCart(@Validated @NotNull(message = "用户id不能为null") Integer userId){
        String itemName = SHOPPINGCART_NAME + userId;
        Object obj = redisTemplate.opsForHash().get(SHOPPINGCART_KEY, itemName);
        if (obj != null) {
            String value = JSONObject.toJSONString(obj);
            ShoppingCart shoppingCart = JSONObject.parseObject(value, new TypeReference<ShoppingCart>(){});
            return shoppingCart;
        } else {
            return null;
        }
    }

    @Override
    public Integer delProductForShoppingCart(@NotNull(message = "用户id不能为null")Integer userId,
                                             @NotNull(message = "商品id不能为null")Integer pid) {
        //查找该用户是否有购物车
        ShoppingCart cart = getShoppingCart(userId);
        if (cart == null) {
            return null;
        }
        ShoppingCart shoppingCart = cart;
        List<ShoppingCartItem> cartItems = shoppingCart.getCartItems();
        BigDecimal total = cart.getTotalPrice();//获取redis中的总价格
        for (int i = 0; i < cartItems.size(); i++) {
            ShoppingCartItem cartItem = cartItems.get(i);
            if (cartItems.get(i).getProductId().equals(pid)) {
                cartItems.get(i).setProductCount(cartItems.get(i).getProductCount() - 1);
                shoppingCart.setTotalNum(shoppingCart.getTotalNum()-1);
                total=total.subtract(cartItems.get(i).getPrice());//价格变化
                if (cartItems.get(i).getProductCount().equals(0)) {
                    cartItems.remove(cartItem);
                }
                break;
            }
        }
        shoppingCart.setTotalPrice(total);//价格变化
        String itemName = SHOPPINGCART_NAME + userId;
        if (shoppingCart.getCartItems().size() == 0) {
            redisTemplate.opsForHash().delete(SHOPPINGCART_KEY, itemName);
        } else {
            redisTemplate.opsForHash().put(SHOPPINGCART_KEY, itemName, shoppingCart);
        }
        return 1;
    }

    @Override
    public Boolean buyShoppingCart(ShoppingCart shoppingCart) {
        //获取redis中购物车信息
        ShoppingCart cart = getShoppingCart(shoppingCart.getUserId());
        if (cart==null){
            return false;
        }
        ShoppingCart oldShoppingCart = cart;

        ShoppingCart buyShoppingCart = new ShoppingCart();
        buyShoppingCart.setUserId(shoppingCart.getUserId());

        ShoppingCart saveShoppingCart = new ShoppingCart();
        saveShoppingCart.setUserId(shoppingCart.getUserId());

        List<ShoppingCartItem> cartItems = oldShoppingCart.getCartItems();
        for (ShoppingCartItem cartItem:cartItems) {
            int i = 0;
            int num = oldShoppingCart.getTotalNum();//总数量
            BigDecimal total = oldShoppingCart.getTotalPrice();//总金额
            for (; i < shoppingCart.getCartItems().size(); i++) {
                if (cartItem.getProductId().equals(shoppingCart.getCartItems().get(i).getProductId())) {
                    buyShoppingCart.getCartItems().add(cartItem);
                    buyShoppingCart.setTotalPrice(shoppingCart.getTotalPrice());
                    buyShoppingCart.setTotalNum(shoppingCart.getTotalNum());
                    num = num - cartItems.get(i).getProductCount();
                    total = total.subtract(buyShoppingCart.getTotalPrice());
                    break;
                }
            }
            if (i>=shoppingCart.getCartItems().size()){
                saveShoppingCart.setTotalNum(num);
                saveShoppingCart.setTotalPrice(total);
                saveShoppingCart.getCartItems().add(cartItem);
            }
        }
        orderByPay(buyShoppingCart);
        //更新redis
        String itemName = SHOPPINGCART_NAME+shoppingCart.getUserId();
        if (saveShoppingCart.getCartItems().size()==0){
            this.removeProduct(shoppingCart.getUserId());
        }else{
            redisTemplate.opsForHash().put(SHOPPINGCART_KEY,itemName,saveShoppingCart);
        }
        return true;
    }

    @Override
    public Integer removeProduct(Integer userId) {
        String itemName = SHOPPINGCART_NAME + userId;
        redisTemplate.opsForHash().delete(SHOPPINGCART_KEY, itemName);
        return null;
    }

    /*
    为数据库中写入订单信息
     */
    private void orderByPay(@Validated ShoppingCart shoppingCart){
        OrderCartVO order = new OrderCartVO();
        String uuid = Uuid.get16UUID();
        order.setOdId(Integer.valueOf(uuid));//订单id
        order.setUserId(shoppingCart.getUserId());//用户id
        order.setOdStatus(0);//订单状态
        order.setComName(shoppingCart.getCartItems().get(0).getProductName());//商品名字
        order.setOdNumber(Long.valueOf(uuid));//订单编号
        order.setOdTime(LocalDateTime.now());//生成时间
        order.setOdPrice(shoppingCart.getTotalPrice());//总金额
        order.setComNum(shoppingCart.getTotalNum());//订单商品总数量
        TbAddressDTO addressDTO = addressMapper.selectOne(new QueryWrapper<TbAddressDTO>().eq("user_id", shoppingCart.getUserId()));
        order.setMStatus(0);
        order.setShAddress(addressDTO.getAdAddress()+addressDTO.getAdDetail());
        order.setShName(addressDTO.getAdName());
        order.setShPhone(Long.valueOf(addressDTO.getAdPhone()));
        int insert = orderCartMapper.insert(order);
        for (ShoppingCartItem cartItem : shoppingCart.getCartItems()) {
            orderCartMapper.boundGoodsAndOrder(order.getOdId(),cartItem.getProductId(),cartItem.getProductCount(),cartItem.getPrice().multiply(cartItem.getPrice()),cartItem.getColorName(),cartItem.getSpeName());
        }
        if(insert!=0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
    }
}
